package light.head.dao.mobile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import light.head.constant.Parm;
import light.head.enm.RESULT;
import light.head.framework.base.BaseDAO;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.DateUtils;
import light.head.model.LeaveManage;

import org.springframework.stereotype.Service;

@Service
public class MobileLeaveManageDAO extends BaseDAO<LeaveManage, Integer> {

	/**
	 * 查询
	 *@param oc		机构编号
	 *@param map	查询条件
	 *@param pb		分页对象
	 *@author yangguanghe [2014-5-27_下午3:49:13]
	 */
	public RESULT findByMap(Integer oc, Map<String, String> map, PageBean pb) {
		
		if (null == oc) return null;
		
		StringBuffer hql = new StringBuffer("FROM LeaveManage l WHERE l.oc = ?");
		List<Object> parm = new ArrayList<Object>();
		
		parm.add(oc);
		
		if (null != map) {
			
			String cuName = map.get(Parm.CUNAME);
			String st = map.get(Parm.ST);
			String et = map.get(Parm.ET);
			String deleted = map.get(Parm.DELETED);
			String cu = map.get(Parm.CU);
			if (isNotNull(deleted)) {
				hql.append(" AND l.deleted = ?");
				parm.add(Boolean.parseBoolean(deleted));
			}
			if (isNotNull(cuName)) {
				hql.append(" AND l.cu IN (SELECT u.code FROM UserInfo u WHERE u.realName LIKE ?)");
				parm.add("%" + cuName + "%");
			}
			if (isNotNull(st) && isNotNull(et)) {
				hql.append(" AND l.ct BETWEEN ? AND ?");
				parm.add(DateUtils.getDateByStr(st, "yyyy-MM-dd"));
				parm.add(DateUtils.getDateByStr(et, "yyyy-MM-dd"));
			} else if (isNotNull(st) && !isNotNull(et)) {
				hql.append(" AND l.ct >= ?");
				parm.add(DateUtils.getDateByStr(st, "yyyy-MM-dd"));
			} else if (!isNotNull(st) && isNotNull(et)) {
				hql.append(" AND l.ct <= ?");
				parm.add(DateUtils.getDateByStr(et, "yyyy-MM-dd"));
			}
			if(isNotNull(cu)) {
				hql.append(" AND l.cu = ?");
				parm.add(Integer.parseInt(cu));
			}
		}
		
		hql.append(" ORDER BY l.code");
		return findToPageBean(hql.toString(), pb, parm);
	}
	
	public RESULT update(LeaveManage lm) {
		if (null == lm || null == lm.getCode()) return RESULT.PARAMETER_ERROR;
		
		LeaveManage db = super.get(lm.getCode());
		
		if (null == db) return RESULT.NOT_FIND;
		
		boolean ok = false;
		
		if (null == db.getSt() || (null != lm.getSt() && !lm.getSt().equals(db.getSt().toString()))) {
			db.setSt(lm.getSt());
			ok = true;
		}
		
		if (null == db.getEt() || (null != lm.getEt() && !lm.getEt().toString().equals(db.getEt().toString()))) {
			db.setEt(lm.getEt());
			ok = true;
		}
		
		if (null == db.getDeleted() || (null != lm.getDeleted() && lm.getDeleted().booleanValue() != db.getDeleted().booleanValue())) {
			db.setDeleted(lm.getDeleted());
			ok = true;
		}
		
		if (null == db.getReason() || (null != lm.getReason() && !lm.getReason().equals(db.getReason()))) {
			db.setReason(lm.getReason());
			ok = true;
		}
		
		
		if (ok)
			return	super.upd(db);
			
		return RESULT.SUCCESS;
	}
}
